<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 新增角色按钮 -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addRoleDialog = true"
            >
              新增角色
            </el-button>

            <!-- 表格 -->
            <el-table v-loading="loading" :data="roleList" style="width: 100%">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="index"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="name" label="角色名称" width="width" align="center">
              </el-table-column>
              <el-table-column
                prop="description"
                label="描述"
                width="width"
                align="center"
              ></el-table-column>
              <el-table-column prop="" label="操作" width="400" align="center">
                <template slot-scope="{ row }">
                  <el-button
                    type="success"
                    size="small"
                    @click="clickShowAssignDialog(row.id)"
                  >
                    分配权限
                  </el-button>
                  <el-button type="primary" size="small" @click="edit(row.id)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="del(row.id)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- /表格 -->

            <!-- 分页 -->
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-size="pagesize"
              :page-sizes="[2, 4, 6, 10]"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
            <!-- /分页 -->

            <!-- 添加和编辑的弹出框 -->
            <el-dialog
              :title="formRole.id ? '编辑角色' : '添加角色'"
              :visible.sync="addRoleDialog"
              @close="closeAddRole"
            >
              <div>
                <el-form
                  ref="formRole"
                  :model="formRole"
                  label-width="80px"
                  :rules="rules"
                >
                  <el-form-item label="角色名称" prop="name">
                    <el-input
                      v-model="formRole.name"
                      placeholder="请输入角色名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="角色描述" prop="description">
                    <el-input
                      v-model="formRole.description"
                      placeholder="请输入角色描述"
                    ></el-input>
                  </el-form-item>
                </el-form>
              </div>
              <div slot="footer">
                <el-button @click="addRoleDialog = false">取 消</el-button>
                <el-button type="primary" @click="addRoleConfirm">确 定</el-button>
              </div>
            </el-dialog>
            <!-- /添加和编辑的弹出框 -->

            <!-- 分配权限弹出层 -->
            <el-dialog
              title="分配权限"
              :visible.sync="showAssignDialog"
              @open="openAssignDialog"
            >
              <el-tree
                ref="tree"
                v-loading="loadingAssign"
                :data="permissionList"
                :props="{ label: 'name' }"
                :default-expand-all="true"
                :show-checkbox="true"
                :check-strictly="true"
                node-key="id"
              >
              </el-tree>
              <div slot="footer">
                <el-button @click="showAssignDialog = false">取 消</el-button>
                <el-button type="primary" @click="editAssign">
                  确 定
                </el-button>
              </div>
            </el-dialog>
            <!-- /分配权限弹出层 -->
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <el-alert :title="message" type="info" show-icon :closable="false">
            </el-alert>
            <el-form ref="companyForm" :model="companyForm" label-width="80px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width:400px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width:400px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width:400px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  disabled
                  style="width:400px;"
                  resize="none"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  reqDelRoleById,
  reqGetRoleById,
  reqGetRoleList,
  reqPostAddRole,
  reqEditRoleById,
  reqEditPermIds,
} from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermission } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'

export default {
  name: 'RoleSetting',
  data() {
    return {
      activeName: 'role', // tab栏高亮
      loading: false, // loading状态
      // 表格的数据
      roleList: [
        { date: '2016-05-02', name: '王小虎' },
        { date: '2016-05-04', name: '王小虎' },
        { date: '2016-05-01', name: '王小虎' },
        { date: '2016-05-03', name: '王小虎' },
      ],
      page: 1, // 页码
      pagesize: 2, // 每页条数
      total: 10, // 总条数
      addRoleDialog: false, // 控制弹出框的显示
      // 弹出层角色表单
      formRole: {
        name: '',
        description: '',
      },
      // 校验规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
        ],
      },
      // 公司信息表单数据
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: '',
      },
      message:
        '对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改',
      // 控制分配权限弹出层的布尔值
      showAssignDialog: false,
      // 控制分配权限loading状态
      loadingAssign: false,
      permissionList: [], // 权限列表
      userId: '',
    }
  },
  computed: {
    // 获取公司id
    ...mapState('user', ['userInfo']),
  },
  watch: {
    // 监听当前tab栏在哪一个,如果是company,那么就发送请求获取公司信息并赋值
    activeName: {
      immediate: true,
      async handler(value) {
        if (value === 'company') {
          if (!this.companyForm.id) {
            const data = await reqGetCompanyById(this.userInfo.companyId)
            this.companyForm = data
          }
        }
      },
    },
  },
  created() {
    // 调用加载表格数据的方法
    this.loadRoleList()
  },
  methods: {
    // 表格索引方法
    index(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },

    // 一、加载表格数据
    async loadRoleList() {
      this.loading = true
      // 1.发送请求,保存数据
      const data = await reqGetRoleList(this.page, this.pagesize)
      // console.log(data)
      this.$message.success('获取角色列表成功')
      this.roleList = data.rows
      this.total = data.total
      this.loading = false
    },

    // 二、页码改变时触发的函数
    handleCurrentChange(page) {
      // console.log(page)
      this.page = page
      this.loadRoleList()
    },

    // 三、每页数量发生改变时触发的函数
    handleSizeChange(pagesize) {
      this.pagesize = pagesize
      this.loadRoleList()
    },

    // 四、删除角色功能
    async del(id) {
      // console.log(id)
      // 1.弹出提示框
      try {
        await this.$confirm('你忍心删除我吗? T.T', '温馨提示', { type: 'warning' })
        // 2.发送删除请求
        try {
          await reqDelRoleById(id)
          if (this.roleList.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.loadRoleList()
        } catch {
          // this.$message.error('删除失败')
        }
      } catch {
        this.$message.info('取消')
      }
    },

    // 五、点击弹出框的确认按钮触发的事件
    addRoleConfirm() {
      // 1.对表单进行校验
      this.$refs['formRole'].validate(async valid => {
        if (!valid) return this.$message.error('请填写必须项')
        // (1)校验通过,发送添加请求
        // (2)通过判断有无id来确认到底是发送添加还是编辑请求
        if (this.formRole.id) {
          // 1.1 有id 编辑角色请求
          try {
            await reqEditRoleById(this.formRole.id, this.formRole)
            this.$message.success('修改成功')
          } catch (error) {
            this.$message.error('修改失败')
          }
        } else {
          // 1.2 没有id 添加角色请求
          try {
            await reqPostAddRole(this.formRole)
            this.$message.success('添加成功')
          } catch (err) {
            this.$message.success('添加失败')
          }
        }
        // 1.3 关闭弹出层,刷新数据
        this.addRoleDialog = false
        this.loadRoleList()
      })
    },

    // 七、关闭弹出层触发的事件
    closeAddRole() {
      // console.log('关闭了')
      this.formRole = {}
    },

    // 八、点击编辑按钮,弹出对话框,并进行表单赋值
    async edit(id) {
      // console.log(id)
      // 1.弹出对话框
      this.addRoleDialog = true
      // 2.根据id获取角色详情
      const data = await reqGetRoleById(id)
      // console.log(data)
      this.formRole = data
    },

    // 九、点击分配权限,显示弹出层
    clickShowAssignDialog(id) {
      this.showAssignDialog = true
      this.userId = id
    },

    // 十、打开弹出层触发
    async openAssignDialog() {
      // console.log(this.userId)
      // 1.打开loading状态
      this.loadingAssign = true
      // 2.获取权限列表,并转换成树形结构
      const permissionList = await reqGetPermission()
      this.permissionList = tranListToTreeData(permissionList, '0')
      // 3.获取角色详情信息
      const roleDetail = await reqGetRoleById(this.userId)
      // console.log(roleDetail.permIds)
      // 4.回显权限
      this.$refs.tree.setCheckedKeys(roleDetail.permIds)
      // 5.关闭loading状态
      this.loadingAssign = false
    },

    // 十一、确定修改权限
    async editAssign() {
      // 1.发送请求
      await reqEditPermIds({
        id: this.userId,
        permIds: this.$refs.tree.getCheckedKeys(),
      })
      this.$message.success('分配权限成功')
      // 2.关闭弹出层
      this.showAssignDialog = false
    },
  },
}
</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
}
.el-alert {
  margin: 10px 0 30px 0;
}
::v-deep {
  .el-tree-node__expand-icon.expanded,
  .el-tree-node__expand-icon.is-leaf,
  .el-tree-node__content > .el-tree-node__expand-icon {
    display: none;
  }
}
</style>
